package com.study.common.jpush.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.JsonObject;
import com.study.common.config.JPushConfig;
import com.study.common.jpush.domain.PushBean;
import com.study.common.jpush.service.IJPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class JPushServiceImpl implements IJPushService {

    private final JPushConfig jPushConfig;

    /**
     * 广播推送所有(所有平台，所有设备，不支持附加信息)
     *
     * @param pushBean
     * @return
     */
    @Override
    public boolean pushAll(PushBean pushBean) {
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(Notification.alert(pushBean.getAlert()))
                .build());
    }

    /**
     * IOS广播推送
     *
     * @param pushBean
     * @return
     */
    @Override
    public boolean pushIos(PushBean pushBean) {
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.all())
                .setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
                .build());
    }

    /**
     * IOS 通过registids指定推送，（一次推送最多1000个）
     *
     * @param pushBean
     * @param registids
     * @return
     */
    @Override
    public boolean pushIos(PushBean pushBean, String... registids) {
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.registrationId(registids))
                .setNotification(Notification.ios(pushBean.getAlert(), pushBean.getExtras()))
                .build());
    }

    /**
     * Android 通过registids指定推送，（一次推送最多1000个）
     *
     * @param pushBean
     * @return
     */
    @Override
    public boolean pushAndroid(PushBean pushBean) {
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.all())
                .setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
                .build());
    }

    @Override
    public boolean pushAndroid(PushBean pushBean, String... registids) {
        return sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.registrationId(registids))
                .setNotification(Notification.android(pushBean.getAlert(), pushBean.getTitle(), pushBean.getExtras()))
                .build());
    }

    @Override
    public boolean pushUserKey(PushBean pushBean, String deviceToken) {
        JsonObject intent = new JsonObject();
        intent.addProperty("url", "intent:#Intent;action=android.intent.action.MAIN;end");
        return sendPush(PushPayload.newBuilder().setPlatform(Platform.all())
                .setAudience(
                        Audience.registrationId(deviceToken)
                )
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder() //发送ios
                                .setAlert(pushBean.getAlert()) //消息体
                                .setBadge(+1)
                                .setSound("happy") //ios提示音
                                .addExtras(pushBean.getExtras()) //附加参数
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder() //发送android
                                .addExtras(pushBean.getExtras()) //附加参数
                                .setAlert(pushBean.getAlert())
                                .setIntent(intent)//消息体
                                .build())
                        .build())
                .setMessage(
                        Message.newBuilder()
                                .setTitle(pushBean.getTitle())
                                .setMsgContent(pushBean.getAlert())
                                .addExtras(pushBean.getExtras())
                                .build()
                )
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                .build());
    }

    /**
     * 消息推送出去
     *
     * @param pushPayload 推送实体
     * @return
     */
    @Override
    public boolean sendPush(PushPayload pushPayload) {
        log.info("发送极光推送请求:{}", pushPayload);

        PushResult pushResult = null;
        try {
            pushResult = jPushConfig.getjPushClient().sendPush(pushPayload);
        } catch (APIConnectionException e) {
            log.error("极光推送推送链接异常:{}", e, pushPayload);
        } catch (APIRequestException e) {
            log.error("极光推送推送链接异常:{}", e, pushPayload);
        }
        if (pushResult != null && pushResult.isResultOK()) {
            log.info("极光推送发送成功:{}", pushResult);
            return true;
        } else {
            log.info("极光推送发送失败:{}", pushResult);
            return false;
        }

    }
}
